package org.bootstrap.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.bootstrap.entity.UserInfo;
import org.bootstrap.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceAdminImpl {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserServiceImpl userServiceImpl;

    public JSONObject set_status(HashMap<String, String> params) {
        JSONObject res = JSONUtil.createObj();
        int code = 200;
        String msg = "";
        if (params.isEmpty()) {
            code = 404; // 传入参数有误
            msg = "缺少参数";
        } else {
            JSONObject userVerity = userServiceImpl.user_verity(params);
            if (userVerity.containsKey("login") && !userVerity.getBool("login")) {
                // token 过期
                msg = "登录已过期";
                code = 401;
            } else {
                JSONObject info = userVerity.getJSONObject("user_info");
                if (params.containsKey("order")) {
                    int row = -1;
                    String userId = info.getStr("user_id");
                    switch (params.get("order")) {
                        case "disable":
                            row = userMapper.set_status(userId, 1);
                            break;
                        case "enable":
                            row = userMapper.set_status(userId, 0);
                            break;
                    }
                }
            }
        }
        res.putOpt("code", code)
                .putOpt("msg", msg);
        return res;
    }


    // 验证是否是超级管理员
    public synchronized JSONObject verity_admin(HashMap<String, String> params) {
        JSONObject query = userServiceImpl.user_verity(params);
        if (Objects.isNull(query) || query.isEmpty()) {
            return null;
        }
        UserInfo userInfo = query.get("user_info", UserInfo.class);
        query.clear();
        if (ObjectUtil.isNotNull(userInfo)) {
            query.putOpt("is_admin", userServiceImpl.is_admin(userInfo.getUser_id()))
                    .putOpt("msg", "认证成功");
        } else {
            query.putOpt("code", 400)
                    .putOpt("msg", "权限认证失败");
        }
        return query;
    }
}
